/**
 * com.dingjian.base.dao.impl.BaseDaoImpl.java
 * 2012-6-19
 */
package com.dingjian.base.dao.impl;

import java.util.List;
import java.util.UUID;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionUtils;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.dingjian.base.CoreEntity;
import com.dingjian.base.dao.BaseDao;
import com.dingjian.base.util.StringUtils;

/**
 * Dao基础实现
 * @author FengMy
 * @since 2012-6-19下午05:47:22
 */
public abstract class BaseDaoImpl extends SqlSessionDaoSupport implements BaseDao {
	@Autowired
	protected SqlSessionFactory sqlSessionFactory;
	@Autowired
	protected JdbcTemplate jdbcTemplate;
	
	protected abstract String getNameSpace();
	
	@Override
	public <T> void addEntity(T entity) {
		if(entity instanceof CoreEntity && StringUtils.isEmpty(((CoreEntity)entity).getId())){
			((CoreEntity)entity).setId(UUID.randomUUID().toString());
		}
		getSqlSession().insert(getNameSpace()+".insert", entity);
	}
	@Override
	public <T> void updateEntity(T entity) {
		getSqlSession().update(getNameSpace()+".update", entity);
	}
	@Override
	public <T> void deleteEntity(T entity) {
		if(entity instanceof CoreEntity){
			getSqlSession().delete(getNameSpace()+".delete", ((CoreEntity)entity).getId());
		}else{
			getSqlSession().delete(getNameSpace()+".delete", entity);
		}
	}
	@Override
	public void deleteById(String id) {
		deleteEntity(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T extends CoreEntity> T getEntityById(String id) {
		return (T) getSqlSession().selectOne(getNameSpace()+".getById", id);
	}
	
	@Override
	public <T> void addBatch(List<T> entities) {
		for(T entity : entities){
			addEntity(entity);
		}
	}
	
	@Override
	public <T> void updateBatch(List<T> entities) {
		for(T entity : entities){
			updateEntity(entity);
		}
	}
	
	@Override
	public <T> void deleteBatch(List<String> ids) {
		for(String id : ids){
			deleteById(id);
		}
	}
}
